package cn.swust.designpatternlearningplatform.handler;

import cn.swust.designpatternlearningplatform.event.TopicWrongEvent;
import cn.swust.designpatternlearningplatform.service.TopicWrongService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class TopicWrongHandler implements ApplicationListener<TopicWrongEvent> {

    private final Map<String, List<TopicWrongEvent>> studentTopicWrongList = new ConcurrentHashMap<>();
    @Resource
    private TopicWrongService topicWrongService;

    /**
     * 消费错题事件
     *
     * @param event
     * @return void
     * @author Tang
     * @date 2023/9/23 9:56
     **/
    @Override
    public void onApplicationEvent(TopicWrongEvent event) {
        String studentNumber = event.getStudentNumber();
        if (!studentTopicWrongList.containsKey(studentNumber)) {
            List<TopicWrongEvent> topics = new Vector<>();
            studentTopicWrongList.put(studentNumber, topics);
        }
        List<TopicWrongEvent> topicIds = studentTopicWrongList.get(studentNumber);
        topicIds.add(event);
    }

    @Scheduled(cron = "*/5 * * * * *")
    public void RegularlyUpdateErrorInformation() {
        Set<String> studentNumbers = getStudents();
        if (studentNumbers.isEmpty()) {
            return;
        }
        for (String studentNumber : studentNumbers) {
            try {
                List<TopicWrongEvent> wrongEvents = getTopicIds(studentNumber);
                topicWrongService.submitTopicWrong(studentNumber, wrongEvents);
            } finally {
                studentNumbers.remove(studentNumber);
            }
        }
        log.info("存入错题");
    }

    /**
     * 获取当前需要处理错题的学生学号
     *
     * @param
     * @return java.util.Set<java.lang.String>
     * @author Tang
     * @date 2023/9/23 9:58
     **/
    public Set<String> getStudents() {
        return studentTopicWrongList.keySet();
    }

    /**
     * 获取指定学生的当前的错题
     *
     * @param studentNumber
     * @return java.util.List<java.lang.Integer>
     * @author Tang
     * @date 2023/9/23 9:59
     **/
    public List<TopicWrongEvent> getTopicIds(String studentNumber) {
        return studentTopicWrongList.get(studentNumber);
    }

}
